import React, {useEffect, useState} from 'react';
import {Container} from './style'

import { Layout, Menu, Breadcrumb, Tooltip, Dropdown, Tabs, Drawer, Badge, List, Avatar, Tag, Modal, Button, Space } from 'antd';
import {
	DesktopOutlined,
    UserOutlined,
    StockOutlined,
    EditOutlined,
    HistoryOutlined,
    ToolOutlined,
    FilePptOutlined,
    RobotOutlined,
    SettingOutlined,
    QuestionCircleOutlined,
    BellOutlined,
    LogoutOutlined,
    DeleteOutlined,
    MoreOutlined,
    MailOutlined,
    ExclamationCircleOutlined,
    ControlOutlined
} from '@ant-design/icons';

import defaultSettings from '../../defaultSettings'

import LoginRequest from '../../request/login_request'
import MyRequest from '../../request/my_request'

import {changeUserInfo} from '../../store/actionCreators'


import TimeTitle from '../../components/TimeTitle'

import {connect} from 'react-redux'

import ws from '../../ws'

import {Route, Redirect, withRouter, Switch} from 'react-router-dom'

import LazyRouter from '../../components/LazyRouter'

// import Workplace from './workplace'
const Workplace = LazyRouter(() => import('./workplace'))

// import DevelopTool from './developTool'
const DevelopTool = LazyRouter(() => import('./developTool'))
const JuejinContents = LazyRouter(() => import('./developTool/juejinContents'))

// import PlanMonitor from './plan/planMonitor'
const PlanMonitor = LazyRouter(() => import('./plan/planMonitor'))
// import PlanMake from './plan/planMake'
const PlanMake = LazyRouter(() => import('./plan/planMake'))
// import PlanHistory from './plan/planHistory'
const PlanHistory = LazyRouter(() => import('./plan/planHistory'))

// import MyCenter from './my/myCenter'
const MyCenter = LazyRouter(() => import('./my/myCenter'))
// import MyNotice from './my/myNotice'
const MyNotice = LazyRouter(() => import('./my/myNotice'))
// import MySetting from './my/mySetting'
const MySetting = LazyRouter(() => import('./my/mySetting'))

const BlogAdmin = LazyRouter(() => import('./admin/blogAdmin'))
const FriendlyLinkAdmin = LazyRouter(() => import('./admin/friendlyLinkAdmin'))
const FeedbackAdmin = LazyRouter(() => import('./admin/feedbackAdmin'))
const HomeAdmin = LazyRouter(() => import('./admin/homeAdmin'))
const ToolAdmin = LazyRouter(() => import('./admin/toolAdmin'))
const UserAdmin = LazyRouter(() => import('./admin/userAdmin'))
const DraftsAdmin = LazyRouter(() => import('./admin/draftsAdmin'))

// import Page404 from '../abnormal/page404'
const Page404 = LazyRouter(() => import('../abnormal/page404'))


const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;
const { TabPane } = Tabs;
const { confirm } = Modal;

const login_request = new LoginRequest()
const my_request = new MyRequest()


function Main(props) {
    const {history, location, userInfo, changeUserInfo} = props

    const [currentOpenKeys, setCurrentOpenKeys] = useState(['/main/workplace'])
    const [currentSelectedKeys, setCurrentSelectedKeys] = useState([])

    const [noticeListVisible, setNoticeListVisible] = useState(false)

    const [newMsg, setNewMsg] = useState(0)

    const noticeList = [
        {
          title: '您的账号存在风险',
        },
        {
          title: '版本重大升级',
        },
        {
          title: '九月重阳，情回故里',
        },
        {
          title: '系统消息',
        },
      ]
    const msgList = [
        {
            title: '陈萍萍 评论了你',
            content: '[8:29] 你是傻逼吧'
          },
          {
            title: '及你太美 点赞了你',
            content: '[8:29] 你是傻逼吧'
          },
          {
            title: '花儿为什么那么红 点赞了你',
            content: '[8:29] 你是傻逼吧'
          },
          {
            title: '你是来拉*的吧 评论了你',
            content: '[8:29] 你是傻逼吧'
          },
    ]
    const waitList = [
        {
            title: '计划一件事情',
            content: '计划在明天完成'
        },
        {
            title: '计划一件事情',
            content: '计划在明天完成'
        },{
            title: '计划一件事情',
            content: '计划在明天完成'
        },{
            title: '计划一件事情',
            content: '计划在明天完成'
        },{
            title: '计划一件事情',
            content: '计划在明天完成'
        },
    ]
    const handleClickMenu = (e) => {
        if(e.key === '/login'){
            confirm({
                title: '是否现在退出登录?',
                icon: <ExclamationCircleOutlined />,
                content: '现在退出登录将无法正常使用本站，确认退出？',
                okText: '立即退出',
                okType: 'danger',
                cancelText: '暂不',
                onOk() {
                    return new Promise((resolve, reject) => {
                        login_request.logout().then(res => {
                            history.replace('/login')
                            resolve()
                        }).catch(() => {
                            reject()
                        })
                    })
                },
                onCancel() {},
            })
        }else{
            history.push(e.key)
        }
    }
    //存储用户信息
    const saveUserInfo = () => {
        my_request.getUserInfo({
            forceLogin: true
        }).then(res => {
            changeUserInfo(res.userinfo)
        }).catch(err => {
            if(err === 304){
                setTimeout(() => {
                    history.replace('/login')
                }, 1500)
            }
        })
    }
    const handleOpenChange = (openKeys) => {
        setCurrentOpenKeys(openKeys)
    }
    const avatarMenu = (
        <Menu onClick={handleClickMenu} style={{width: 150}}>
            <Menu.Item key="/main/my/myCenter">
                <UserOutlined />
                {defaultSettings.paths['myCenter']}
            </Menu.Item>
            <Menu.Item key="/main/my/mySetting">
                <SettingOutlined />
                {defaultSettings.paths['mySetting']}
            </Menu.Item>
            <Menu.Divider />
            <Menu.Item key="/login">
                <LogoutOutlined />
                {defaultSettings.paths['login']}
            </Menu.Item>
        </Menu>
    )

    const goToAdmin = (path) => {
        history.push('/main/' + path)
    }

    useEffect(() => {
        setCurrentSelectedKeys([location.pathname])
    }, [location])

    useEffect(() => {
        setCurrentOpenKeys([location.pathname.substring(1).split('/')[1]])
        saveUserInfo()

        //监听系统通知
        ws.on('count', (msg) => {
            setNewMsg(msg || 0)
            // console.log(msg)
        })
    }, [])

	return (
		<Container>
            <Layout style={{ minHeight: '100vh' }}>
                <Sider collapsible trigger={null} style={{overflow: 'auto', height: '100vh', position: 'fixed', left: 0, }}>
                    <div className="logo">
                        <img src={defaultSettings.webUrl} alt=""/>
                        <span>{defaultSettings.title}</span>
                    </div>
                    <Menu theme="dark" selectedKeys={currentSelectedKeys} openKeys={currentOpenKeys} mode="inline" onClick={handleClickMenu} onOpenChange={handleOpenChange}>
                        <Menu.Item key="/main/workplace">
                            <DesktopOutlined />
                            <span>{defaultSettings.paths['workplace']}</span>
                        </Menu.Item>
                        <Menu.Item key="/main/developtool">
                            <ToolOutlined />
                            <span>{defaultSettings.paths['developtool']}</span>
                        </Menu.Item>
                        <SubMenu
                            key="plan"
                            title={
                                <span>
                                    <FilePptOutlined />
                                    <span>{defaultSettings.paths['plan']}</span>
                                </span>
                            }
                        >
                            <Menu.Item key="/main/plan/planMonitor">
                                <StockOutlined />
                                {defaultSettings.paths['planMonitor']}
                            </Menu.Item>
                            <Menu.Item key="/main/plan/planMake">
                                <EditOutlined />
                                {defaultSettings.paths['planMake']}
                            </Menu.Item>
                            <Menu.Item key="/main/plan/planHistory">
                                <HistoryOutlined />
                                {defaultSettings.paths['planHistory']}
                            </Menu.Item>
                        </SubMenu>
                        <SubMenu
                            key="my"
                            title={
                                <span>
                                    <RobotOutlined />
                                    <span>{defaultSettings.paths['my']}</span>
                                </span>
                            }
                        >
                            <Menu.Item key="/main/my/myCenter">
                                <UserOutlined />
                                {defaultSettings.paths['myCenter']}
                            </Menu.Item>
                            <Menu.Item key="/main/my/myNotice">
                                <BellOutlined />
                                {defaultSettings.paths['myNotice']}
                            </Menu.Item>
                            <Menu.Item key="/main/my/mySetting">
                                <SettingOutlined />
                                {defaultSettings.paths['mySetting']}
                            </Menu.Item>
                        </SubMenu>
                        {
                            (userInfo.authority === 'super' || userInfo.authority === 'admin') ? 
                            <SubMenu
                                key="admin"
                                title={
                                    <span>
                                        <ControlOutlined />
                                        <span>{defaultSettings.paths['admin']}</span>
                                    </span>
                                }
                            >
                                <Menu.Item key="/main/admin/blogAdmin">
                                    {defaultSettings.paths['blogAdmin']}
                                </Menu.Item>
                                <Menu.Item key="/main/admin/friendlyLinkAdmin">
                                    {defaultSettings.paths['friendlyLinkAdmin']}
                                </Menu.Item>
                                <Menu.Item key="/main/admin/feedbackAdmin">
                                    {defaultSettings.paths['feedbackAdmin']}
                                </Menu.Item>
                                <Menu.Item key="/main/admin/homeAdmin">
                                    {defaultSettings.paths['homeAdmin']}
                                </Menu.Item>
                                <Menu.Item key="/main/admin/toolAdmin">
                                    {defaultSettings.paths['toolAdmin']}
                                </Menu.Item>
                                <Menu.Item key="/main/admin/userAdmin">
                                    {defaultSettings.paths['userAdmin']}
                                </Menu.Item>
                                <Menu.Item key="/main/admin/draftsAdmin">
                                    {defaultSettings.paths['draftsAdmin']}
                                </Menu.Item>
                            </SubMenu>
                            : ''
                        }
                    </Menu>
                </Sider>
                <Layout className="site-layout" style={{ marginLeft: 200 }}>
                    <Header className="site-layout-background" style={{ position: 'fixed', zIndex: 1, width: 'calc(100% - 200px)', padding: '0 20px' }}>
                        <div className="header-left">
                            <TimeTitle></TimeTitle>
                        </div>
                        <div className="header-right">
                            <div className="header-right-item">
                                <Button type="dashed" onClick={() => history.push('/article')}>站长的博客</Button>
                            </div>

                            <Tooltip title="本站须知" placement="bottom">
                                <div className="header-right-item">
                                    <QuestionCircleOutlined style={{padding: 4, fontSize: 16}}/>
                                </div>
                            </Tooltip>
                            
                            
                            <div className="header-right-item" onClick={() => setNoticeListVisible(true)}>
                                <Badge count={newMsg}>
                                    <BellOutlined style={{padding: 4, fontSize: 16}}/>
                                </Badge>
                            </div>
                            
                            <Dropdown overlay={avatarMenu} placement="bottomRight">
                                <div className="header-right-item">
                                    <Avatar src={userInfo.avatar || defaultSettings.defaultAvatar} size={24} style={{marginRight: 8}}/>
                                    {userInfo.username}
                                </div>
                            </Dropdown>
                        </div>
                    </Header>
                    <Content style={{ margin: '16px 0', marginTop: 64}}>
                        <div style={{background: `url(${require('../../assets/img/home_bg.png')})`, backgroundSize: 'cover', backgroundPosition: '50%', padding: 16, marginTop: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
                            <Breadcrumb style={{ margin: '0 16px' }}>
                                {
                                    location.pathname.substring(1).split('/').map((item, index) => {
                                        return <Breadcrumb.Item key={index}>{defaultSettings.paths[item]}</Breadcrumb.Item>
                                    })
                                }
                            </Breadcrumb>
                        </div>
                        
                        <div className="content">
                            <Switch>
                                <Route path="/main" exact render={() => <Redirect to="/main/workplace"></Redirect>}></Route>
                                <Route path="/main/workplace" component={Workplace}></Route>
                                <Route path="/main/developtool" exact component={DevelopTool}></Route>
                                <Route path="/main/developtool/juejinContents" component={JuejinContents}></Route>
                                <Route path="/main/plan/planMonitor" component={PlanMonitor}></Route>
                                <Route path="/main/plan/planMake" component={PlanMake}></Route>
                                <Route path="/main/plan/planHistory" component={PlanHistory}></Route>
                                <Route path="/main/my/myCenter" component={MyCenter}></Route>
                                <Route path="/main/my/myNotice" component={MyNotice}></Route>
                                <Route path="/main/my/mySetting" component={MySetting}></Route>

                                <Route path="/main/admin/blogAdmin" component={BlogAdmin}></Route>
                                <Route path="/main/admin/friendlyLinkAdmin" component={FriendlyLinkAdmin}></Route>
                                <Route path="/main/admin/feedbackAdmin" component={FeedbackAdmin}></Route>
                                <Route path="/main/admin/homeAdmin" component={HomeAdmin}></Route>
                                <Route path="/main/admin/toolAdmin" component={ToolAdmin}></Route>
                                <Route path="/main/admin/userAdmin" component={UserAdmin}></Route>
                                <Route path="/main/admin/draftsAdmin" component={DraftsAdmin}></Route>
                                
                                <Route path="/main/page404" component={Page404}></Route>
                                <Route render={() => <Redirect to="/main/page404"></Redirect>}></Route>
                            </Switch>
                        </div>
                    </Content>
                    <Footer style={{ textAlign: 'center' }}>
                        <div>{defaultSettings.title} ©2020 Created by {defaultSettings.author}</div>
                        <div className="beian">
                            <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=43010302001140">
                                <img src={require("../../assets/img/ga.png")}/>
                                湘公网安备 43010302001140号
                            </a>
                            <a target="_blank" href="http://beian.miit.gov.cn">湘ICP备20013444号-1</a>
                        </div>
                    </Footer>
                </Layout>
            </Layout>
            <Drawer
                placement="right"
                closable={false}
                bodyStyle={{padding: 0}}
                width={360}
                onClose={() => setNoticeListVisible(false)}
                visible={noticeListVisible}
                style={{ position: 'absolute' }}
            >
                <div className="notice-drawer">
                    <div className="drawer-left">
                        <Tooltip placement="left" title='清空'>
                            <div className="left-item">
                                <DeleteOutlined style={{fontSize: 18}}/>
                            </div>
                        </Tooltip>
                        <Tooltip placement="left" title='查看更多'>
                            <div className="left-item">
                                <MoreOutlined style={{fontSize: 18}}/>
                            </div>
                        </Tooltip>
                    </div>
                    <div className="drawer-right">
                        <Tabs defaultActiveKey="1" size="large">
                            <TabPane tab="通知" key="1">
                                <div className="drawer-tabs">
                                    <List
                                        itemLayout="horizontal"
                                        dataSource={noticeList}
                                        renderItem={item => (
                                        <List.Item>
                                            <List.Item.Meta
                                            avatar={<Avatar style={{ backgroundColor: '#fe5d58' }} icon={<MailOutlined />} />}
                                            title={item.title}
                                            description="3年前"
                                            />
                                        </List.Item>
                                        )}
                                    />
                                </div>
                            </TabPane>
                            <TabPane tab="消息" key="2">
                                <div className="drawer-tabs">
                                    <List
                                        itemLayout="horizontal"
                                        dataSource={msgList}
                                        renderItem={item => (
                                        <List.Item>
                                            <List.Item.Meta
                                            avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
                                            title={item.title}
                                            description={item.content}
                                            />
                                        </List.Item>
                                        )}
                                    />
                                </div>
                            </TabPane>
                            <TabPane tab="待办" key="3">
                                <div className="drawer-tabs">
                                    <List
                                        itemLayout="horizontal"
                                        dataSource={waitList}
                                        renderItem={item => (
                                        <List.Item>
                                            <List.Item.Meta
                                            title={item.title}
                                            description={item.content}
                                            />
                                            <div>
                                                <Tag color="red">马上到期</Tag>
                                            </div>
                                        </List.Item>
                                        )}
                                    />
                                </div>
                            </TabPane>
                        </Tabs>
                    </div>
                </div>
            </Drawer>
		</Container>
	);
}

const mapState = (state) => ({
    userInfo: state.userInfo
})

const mapDispatch = (dispatch) => ({
    changeUserInfo(data){
		dispatch(changeUserInfo(data))
	}
})

export default withRouter(connect(mapState, mapDispatch)(Main));
